<template>
  <div class="app-container">
    <Header></Header>
    <Goods
        v-for="item in list"
        :key="item.id"
        :id="item.id"
        :title="item.goods_name"
        :pic="item.goods_img"
        :price="item.goods_price"
        :count="item.goods_count"
        :state="item.goods_state"
        @state-change="getNewState"
    ></Goods>
    <Footer
        :isFull="this.fullState"
        :amount="amt"
        :total="total"
        @full-change="getFullState"
    ></Footer>
  </div>
</template>

<script>
  // 导入 axios 请求库
  import axios from "axios";
  // 导入需要的组件
  import Header from "@/components/Header/Header.vue";
  import Goods from "@/components/Goods/Goods.vue";
  import Footer from "@/components/Footer/Footer.vue";

  import bus from '@/components/EventBus.js'

  export default {
    created() {
      this.initCartList();

      bus.$on('share', val => {
        console.log("接受到的数据", val)
        this.list.some(item => {
          if (item.id === val.id) {
            item.goods_count = val.value
            return true
          }
        })
      })
    },
    components: {
      Header,
      Goods,
      Footer,
    },
    data() {
      return {
        list: [],
      };
    },
    //计算属性
    computed: {
      fullState() {
        //动态计算全选的状态是true还是false
        return this.list.every(item => item.goods_state)
      },
      amt() {
        return this.list
        .filter(item => item.goods_state)
        .reduce((total, item) => (total += item.goods_price * item.goods_count), 0)
      },
      total() {
        return this.list.filter(item => item.goods_state).reduce((t, item) => (t += item.goods_count), 0)
      }
    },
    methods: {
      async initCartList() {
        const {data: res} = await axios.get("https://www.escook.cn/api/cart");
        if (res.status === 200) {
          this.list = res.list;
        }
        console.log(this.list);
      },
      //接受子组件传递过来的数据
      getNewState(e) {
        console.log(e)
        this.list.some((item) => {
          if (item.id === e.id) {
            item.goods_state = e.value;
            return;
          }
        });
      },
      getFullState(e) {
        console.log(e)
        this.list.forEach(item => item.goods_state = e)
      }
    },

  };
</script>

<style lang="less" scoped>
  .app-container {
    padding-top: 45px;
    padding-bottom: 50px;
  }
</style>
